home *** CD-ROM | disk | FTP | other *** search
- /* bsearch on page 312 of the Turbo C Bible */
- #include <stdio.h>
- #include<string.h>
- #include <stdlib.h>
- int mycompare(const void *, const void *);
- main(int argc, char **argv, char **envp)
- {
- unsigned int i, count;
- char **p_table, **result;
- if(argc <2)
- {
- printf("Usage: %s <KEYWORD>\n", argv[0]);
- exit(0);
- }
- /* Find length of environment table */
- for(count = 0, p_table = envp;
- *p_table !=NULL;
- p_table++, count++); /* a null loop */
- /* Sort the environment table using "qsort" */
- qsort((void *) envp, (size_t)count,
- (size_t)sizeof(char *), mycompare);
- /* Print sorted environment table */
- printf("=+=== Sorted environment table =====\n");
- for(i = 0, p_table = envp; i < count; i++)
- {
- printf("%s\n", *p_table);
- p_table++;
- }
- /* Search for the KEY variable i the environment */
- result = (char **) bsearch((const void *)&argv[1], (const void *)envp,
- (size_t)count, (size_t)sizeof(char *),
- mycompare);
- if(result != NULL)
- printf("\nFound %s in\n%s\n", argv[1], *result);
- else
- printf("\n%s not found. Try with uppercase keyword\n", argv[1]);
- }
- /* ------------------------------ */
- int mycompare(const void *arg1, const void *arg2)
- {
- /* Compare two strigs up to the length of the key */
- return(strncmp(*(char**)arg1, *(char**)arg2, strlen(*(char**)arg1)));
- }